<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\City;
use App\Models\Company;
use App\Models\CompanyCity;
use Illuminate\Http\Request;

class CityController extends Controller
{
    private static function cityFile() {
        return public_path('file/cities.json');
    }

    private static function regionFile() {
        return public_path('file/regions.json');
    }

    // 获取城市
    public function index(Request $i) {
        $cities = json_decode(file_get_contents(self::cityFile()));
        return self::success($cities);
    }

    // 获取区域
    public function region() {
        $regions = json_decode(file_get_contents(self::regionFile()));
        return self::success($regions);
    }

    public static function createCityJson() {
        City::create_city_json(self::cityFile());
    }

    public static function createRegionJson() {
        City::create_region_json(self::regionFile());
    }

    public function import(Request $request) {
        $cities = $request->input('cities');
        $companies = Company::all();
        $com = [];
        foreach($companies as $company) {
            $com[md5($company->name)] = $company->id;
        }

        // 对城市名字进行检查
        foreach($cities as $city) {
            $city['company'] = $com[md5($city['company'])];

            // 对已有的进行检查
            $cityInfo = City::where('name', $city['city'])->first();

            if (empty($cityInfo)) {
                return self::fail(201, "找不到城市[{$city['city']}]");
            }

            $city['city_id']        = $cityInfo->city_id;
            $city['province_id']    = $cityInfo->province_id;
            $city['city_name']      = $cityInfo->city_name;
            $city['province_name']  = $cityInfo->province_name;

            $comCity = CompanyCity::where('company', $city['company'])->where('city_id', $city['city_id'])->first();
            unset($city['city']);
            if ($comCity) {
                $comCity->update($city);
            } else {
                CompanyCity::create($city);
            }
        }

        return self::success();
    }
}
